<template>
    <div class="task-management-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-right">
                    <el-button type="primary" @click="handleAddTask" class="add-task-btn">
                        <el-icon><Plus /></el-icon>
                        新增任务
                    </el-button>
                </div>
            </div>
                </div>

        <!-- 筛选工具栏 -->
        <div class="filter-toolbar">
            <div class="filter-section">
                <!-- 任务类型筛选 -->
                <div class="filter-item">
                    <span class="filter-label">任务类型</span>
                    <el-radio-group v-model="filterForm.taskType" @change="handleFilter" class="compact-radio-group">
                        <el-radio-button :label="0" class="compact-radio">
                            <el-icon><Grid /></el-icon>
                            全部
                        </el-radio-button>
                        <el-radio-button :label="1" class="compact-radio">
                            <el-icon><User /></el-icon>
                            我安排
                        </el-radio-button>
                        <el-radio-button :label="2" class="compact-radio">
                            <el-icon><Avatar /></el-icon>
                            安排我
                        </el-radio-button>
                    </el-radio-group>
            </div>

                <!-- 分隔线 -->
                <div class="filter-divider"></div>

                <!-- 状态筛选 -->
                <div class="filter-item">
                    <span class="filter-label">状态</span>
                    <el-radio-group v-model="filterForm.status" @change="handleFilter" class="compact-radio-group">
                        <el-radio-button :label="0" class="compact-radio">
                            <el-icon><List /></el-icon>
                            全部
                        </el-radio-button>
                        <el-radio-button :label="1" class="compact-radio">
                            <el-icon><Clock /></el-icon>
                            未完成
                        </el-radio-button>
                        <el-radio-button :label="2" class="compact-radio">
                            <el-icon><Check /></el-icon>
                            已完成
                        </el-radio-button>
                    </el-radio-group>
                </div>
            </div>
        </div>

        <!-- 任务列表卡片 -->
        <el-card shadow="never" class="table-card">
            <template #header>
                <div class="table-header">
                    <div class="table-title">
                        <el-icon><List /></el-icon>
                        任务列表
                    </div>
                    <div class="table-stats">
                        <span class="stats-item">
                            <el-icon><Document /></el-icon>
                            共 {{ agencys.total }} 条任务
                        </span>
                    </div>
                </div>
            </template>
            
            <el-table 
                :data="agencys.list || []" 
                class="modern-table"
                v-loading="loading"
                :loading-text="'正在加载任务数据...'"
                empty-text="暂无任务数据"
                stripe
                style="width: 100%"
                :max-height="600"
            >
                <el-table-column prop="itemName" label="项目" width="200" align="center">
                    <template #default="{ row }">
                        <div class="project-cell">
                            <el-icon class="project-icon"><Folder /></el-icon>
                            <span class="project-name">{{ row.itemName }}</span>
                        </div>
                    </template>
                </el-table-column>
                
                <el-table-column prop="manyUserName" :label="filterForm.taskType === 2 ? '安排人' : '被安排人'" width="200" align="center">
                    <template #default="{ row }">
                        <div class="assignee-cell">
                            <div v-if="filterForm.taskType === 2">
                                <!-- 安排我的：显示安排人 -->
                                <div class="assignee-tag">
                                    <el-avatar :size="24" class="assignee-avatar">
                                        {{ row.oneUserName ? row.oneUserName.charAt(0) : '?' }}
                                    </el-avatar>
                                    <span class="assignee-name">{{ row.oneUserName || '未知' }}</span>
                                </div>
                            </div>
                            <div v-else>
                                <!-- 我安排的/全部：显示被安排人 -->
                                <div v-for="name in row.manyUserName.split(',')" :key="name" class="assignee-tag">
                                    <el-avatar :size="24" class="assignee-avatar">
                                        {{ name.charAt(0) }}
                                    </el-avatar>
                                    <span class="assignee-name">{{ name }}</span>
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                
                <el-table-column prop="oneToManyJob" label="任务内容" min-width="400" show-overflow-tooltip>
                    <template #default="{ row }">
                        <div class="task-content">
                            <p class="task-text">
                                {{ row.oneToManyJob }}
                                <el-tooltip 
                                    v-if="isOvertimeDisplay(row)" 
                                    :content="row.overtimeReason || '已超时'" 
                                    placement="top"
                                >
                                    <span class="overtime-badge">超</span>
                                </el-tooltip>
                            </p>
                        </div>
                    </template>
                </el-table-column>
                
                <el-table-column prop="oneToManyTime" label="完成时间" min-width="180" align="center">
                    <template #default="{ row }">
                        <div class="time-cell">
                            <el-icon class="time-icon" :class="{ 'overtime-icon': isOvertimeDisplay(row) }">
                                <Calendar />
                            </el-icon>
                            <span class="time-text" :class="{ 'overtime-text': isOvertimeDisplay(row) }">
                                {{ row.oneToManyTime }}
                            </span>
                        </div>
                    </template>
                </el-table-column>
                
                <el-table-column prop="isTrue1" label="状态" width="120">
                    <template #default="{ row }">
                        <el-tag 
                            :type="row.isTrue1 == 2 ? 'success' : 'warning'" 
                            class="status-tag"
                            :class="{ 'status-completed': row.isTrue1 == 2, 'status-pending': row.isTrue1 != 2 }"
                        >
                            <el-icon>
                                <Check v-if="row.isTrue1 == 2" />
                                <Clock v-else />
                            </el-icon>
                            {{ row.isTrue1 == 2 ? "已完成" : "未完成" }}
                        </el-tag>
                    </template>
                </el-table-column>
                
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <div class="action-buttons">
                            <!-- 安排我的任务：只显示完成按钮 -->
                            <template v-if="filterForm.taskType === 2">
                                <el-button 
                                    size="small" 
                                    type="success" 
                                    @click="completeTask(row)" 
                                    class="action-btn complete-btn"
                                    :disabled="row.isTrue1 == 2"
                                >
                                    <el-icon><Check /></el-icon>
                                    {{ row.isTrue1 == 2 ? '已完成' : '完成' }}
                                </el-button>
                            </template>
                            <!-- 我安排的/全部任务：显示编辑和删除按钮 -->
                            <template v-else>
                                <el-button 
                                    size="small" 
                                    type="primary" 
                                    @click="editTask(row)" 
                                    class="action-btn edit-btn"
                                    :disabled="row.isTrue1 == 2"
                                >
                                    <el-icon><Edit /></el-icon>
                                    编辑
                                </el-button>
                                <el-button 
                                    size="small" 
                                    type="danger" 
                                    @click="deleteTask(row)" 
                                    class="action-btn delete-btn"
                                    :disabled="row.isTrue1 == 2"
                                >
                                    <el-icon><Delete /></el-icon>
                                    删除
                                </el-button>
                            </template>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-wrapper">
                <el-pagination 
                    v-model:current-page="currentPage" 
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 50]" 
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="agencys.total" 
                    @size-change="handleSizeChange" 
                    @current-change="handleCurrentChange"
                    class="modern-pagination"
                />
            </div>
        </el-card>

        <!-- 新增/编辑任务对话框 -->
        <el-dialog 
            v-model="showEditDialog" 
            :title="isEditMode ? '编辑任务' : '新增任务'" 
            width="60%"
            class="task-dialog"
            :close-on-click-modal="false"
        >
            <template #header>
                <div class="dialog-header">
                    <div class="dialog-title">
                        <el-icon class="dialog-icon">
                            <Edit v-if="isEditMode" />
                            <Plus v-else />
                        </el-icon>
                        {{ isEditMode ? '编辑任务' : '新增任务' }}
                    </div>
                </div>
            </template>
            
            <el-form :model="taskForm" :rules="rules" ref="taskFormRef" label-width="120px" class="task-form">
                <el-row :gutter="20">
                    <el-col :span="12">
                <el-form-item label="项目名称" prop="itemId">
                            <el-select 
                                v-model="taskForm.itemId" 
                                placeholder="请选择项目" 
                                filterable 
                                class="form-select"
                            >
                                <el-option 
                                    v-for="project in filteredProjects" 
                                    :key="project.value" 
                                    :label="project.label"
                                    :value="project.value"
                                >
                                    <div class="option-content">
                                        <el-icon><Folder /></el-icon>
                                        <span>{{ project.label }}</span>
                                    </div>
                                </el-option>
                    </el-select>
                </el-form-item>
                    </el-col>
                    <el-col :span="12">
                <el-form-item :label="isEditMode ? '安排人' : '安排人'"
                    :prop="isEditMode ? 'manyUserUUID' : 'manyUserUUIDS'">
                            <el-select 
                                v-if="!isEditMode" 
                                v-model="taskForm.manyUserUUIDS" 
                                placeholder="请选择安排人" 
                                filterable
                                multiple 
                                class="form-select"
                            >
                                <el-option 
                                    v-for="person in staffList" 
                                    :key="person.id" 
                                    :label="person.name"
                                    :value="person.id"
                                >
                                    <div class="option-content">
                                        <el-avatar :size="20">{{ person.name.charAt(0) }}</el-avatar>
                                        <span>{{ person.name }}</span>
                                    </div>
                                </el-option>
                    </el-select>

                            <el-select 
                                v-else 
                                v-model="taskForm.manyUserUUID" 
                                placeholder="请选择安排人" 
                                filterable
                                class="form-select"
                            >
                                <el-option 
                                    v-for="person in staffList" 
                                    :key="person.id" 
                                    :label="person.name"
                                    :value="person.id"
                                >
                                    <div class="option-content">
                                        <el-avatar :size="20">{{ person.name.charAt(0) }}</el-avatar>
                                        <span>{{ person.name }}</span>
                                    </div>
                                </el-option>
                    </el-select>
                </el-form-item>
                    </el-col>
                </el-row>
                
                <el-form-item label="任务内容" prop="oneToManyJob">
                    <el-input 
                        v-model="taskForm.oneToManyJob" 
                        type="textarea" 
                        :rows="6" 
                        placeholder="请输入详细的任务内容，包括具体要求、注意事项等..."
                        class="form-textarea"
                        maxlength="500"
                        show-word-limit
                    />
                </el-form-item>
                
                <el-form-item label="完成时间" prop="oneToManyTime">
                    <el-date-picker 
                        v-model="taskForm.oneToManyTime" 
                        type="datetime" 
                        placeholder="选择完成时间"
                        format="YYYY-MM-DD HH:mm:ss" 
                        value-format="YYYY-MM-DD HH:mm:ss" 
                        class="form-datepicker"
                        :disabled-date="disabledDate" 
                        prefix-icon="Calendar" 
                        clear-icon="CircleClose"
                        :default-time="new Date(2000, 1, 1, 0, 0, 0)"
                        :teleported="false"
                    />
                </el-form-item>
            </el-form>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showEditDialog = false" class="cancel-btn">
                        <el-icon><Close /></el-icon>
                        取消
                    </el-button>
                    <el-button type="primary" @click="submitTask" class="confirm-btn">
                        <el-icon><Check /></el-icon>
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 超时原因对话框 -->
        <el-dialog
            v-model="showOvertimeDialog"
            width="560px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            class="task-dialog overtime-dialog"
            @opened="focusReason"
        >
            <template #header>
                <div class="overtime-dialog-header">
                    <el-icon class="overtime-dialog-icon"><Warning /></el-icon>
                    <div class="overtime-dialog-titles">
                        <div class="title">超时提醒</div>
                        <div class="subtitle">任务已超时，请填写超时原因（不少于5个字）。</div>
                    </div>
                </div>
            </template>

            <div class="overtime-body">
                <el-input
                    ref="overtimeInputRef"
                    v-model="overtimeReason"
                    type="textarea"
                    :rows="6"
                    maxlength="200"
                    show-word-limit
                    placeholder="请详细说明超时原因，例如：因优先处理紧急线上问题，导致本任务延后处理。"
                    class="form-textarea"
                />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelOvertime" class="cancel-btn">取消</el-button>
                    <el-button 
                        type="primary" 
                        :disabled="overtimeReason.trim().length < 5 || submittingOvertime"
                        :loading="submittingOvertime"
                        @click="confirmOvertime"
                        class="confirm-btn"
                    >
                        确认完成
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { 
    Plus, Grid, User, Avatar, List, Clock, Check, 
    Document, Folder, Calendar, Edit, Delete, Close, Warning 
} from '@element-plus/icons-vue';
import { GetItemList, GetGetOnlineTaskGuarantors, GetAgencyList, CreateUpdateAgency, DeleteAgencyById, OverAgencyById } from "@/api/newDemands/index";

interface Task {
    ID: number;
    itemId: number;
    manyUserUUID: string;
    oneToManyJob: string;
    oneToManyTime: string;
    isTrue1: number;
    oneUserName?: string;
}

// 获取所有项目
const filteredProjects = ref<{ value: number, label: string }[]>([])
const getItemList = async () => {
    const { data } = await GetItemList()
    if (data.code == 200) {
        filteredProjects.value = data.data.map((item: any) => ({
            value: item.ID,
            label: item.itemName,
        }))
    } else {
        ElMessage.error(data.msg)
    }
}

// 获取所有用户
interface Staff {
    id: string
    name: string
}
const staffList = ref<Staff[]>([])
const getAllUsers = async () => {
    const { data } = await GetGetOnlineTaskGuarantors()
    if (data.code == 200) {
        staffList.value = [
            { id: 'ALL', name: '全部' },
            ...data.data.map((item: any) => ({
                id: item.uuid,
                name: item.userName,
            }))
        ]
    } else {
        ElMessage.error(data.msg)
    }
}

// 任务表单
const taskForm = reactive({
    itemId: 23,
    manyUserUUIDS: [] as string[],  // 用于新增 - 数组类型
    manyUserUUID: "",               // 用于编辑 - 字符串类型
    oneToManyJob: "",
    oneToManyTime: "",
});

// 筛选表单
const filterForm = reactive({
    assignee: "",
    status: 0, // 默认显示全部状态
    taskType: 0, // 默认显示全部任务：0=全部任务，1=我安排的，2=安排我的
    dateRange: [] as string[],
});

// 任务列表
const agencys = ref<{ list: any[], total: number }>({ list: [], total: 0 });
const loading = ref(false);
const showEditDialog = ref(false);
const isEditMode = ref(false);
const currentTaskId = ref<number>(0);
const taskFormRef = ref<FormInstance>();
// 超时对话框
const showOvertimeDialog = ref(false);
const overtimeReason = ref('');
const submittingOvertime = ref(false);
const currentOvertimeRow = ref<any>(null);
const overtimeInputRef = ref();
const focusReason = () => {
    setTimeout(() => (overtimeInputRef.value as any)?.focus?.(), 0);
};

// 取消超时填写
const cancelOvertime = () => {
    showOvertimeDialog.value = false;
    overtimeReason.value = '';
    currentOvertimeRow.value = null;
};

// 确认超时完成
const confirmOvertime = async () => {
    if (!currentOvertimeRow.value) return;
    const reason = overtimeReason.value.trim();
    if (reason.length < 5) return;
    submittingOvertime.value = true;
    const { data } = await OverAgencyById({ id: currentOvertimeRow.value.ID, overtimeReason: reason });
    submittingOvertime.value = false;
    if (data.code == 200) {
        ElMessage.success('任务已完成（已记录超时原因）');
        showOvertimeDialog.value = false;
        overtimeReason.value = '';
        currentOvertimeRow.value = null;
        getAgencyList();
    } else {
        ElMessage.error(data.msg);
    }
};
// 查询代办数据
const currentPage = ref(1);
const pageSize = ref(10);
const getAgencyList = async () => {
    loading.value = true;
    const params: any = {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: '',
    };
    
    // 根据状态过滤：0=全部状态，1=未完成，2=已完成
    if (filterForm.status === 1) {
        // 未完成：状态不等于2
        params.isTrue = 1;
    } else if (filterForm.status === 2) {
        // 已完成：状态等于2
        params.isTrue = 2;
    }
    
    // 根据任务类型过滤：0=全部任务，1=我安排的，2=安排我的
    if (filterForm.taskType === 1) {
        // 我安排的：传递taskType=1
        params.taskType = 1;
    } else if (filterForm.taskType === 2) {
        // 安排我的：传递taskType=2
        params.taskType = 2;
    }
    
    console.log('查询参数:', params); // 调试日志
    
    const { data } = await GetAgencyList(params);
    loading.value = false;
    
    if (data.code == 200) {
        agencys.value = data.data;
        console.log('查询结果:', data.data); // 调试日志
    } else {
        ElMessage.error(data.msg);
    }
}


// 监听安排人选择变化
watch(() => taskForm.manyUserUUIDS, (newVal) => {
    if (newVal.includes('ALL')) {
        const allStaffIds = staffList.value
            .filter(item => item.id !== 'ALL')
            .map(item => item.id);
        
        // 检查是否已经全选
        const isAllSelected = allStaffIds.length === newVal.length - 1 && 
                             allStaffIds.every(id => newVal.includes(id));
        
        // 如果已经全选则清空，否则全选
        taskForm.manyUserUUIDS = isAllSelected ? [] : allStaffIds;
    }
}, { deep: true });

watch(() => taskForm.manyUserUUID, (newVal) => {
    if (newVal === 'ALL') {
        ElMessage.warning('编辑模式下只能选择单个人员');
        taskForm.manyUserUUID = '';
    }
});

/*监听变量变换 */
watch(
    [
        () => currentPage.value,
        () => pageSize.value,
    ],
    () => {
        getAgencyList();
    }
);

// 状态或任务类型变化时重置到第一页，但不立即查询（避免重复调用）
watch(() => [filterForm.status, filterForm.taskType], () => {
    currentPage.value = 1;
});


// 表单验证规则
const rules = {
    itemId: [{ required: true, message: "请选择项目", trigger: "change" }],
    manyUserUUIDS: [
        {
            required: true,
            message: "请至少选择一个安排人",
            trigger: "change",
            type: 'array',
            min: 1,
            validator: (_rule: any, value: any, callback: any) => {
                if (!isEditMode.value && (!Array.isArray(value) || value.length === 0)) {
                    callback(new Error('请至少选择一个安排人'));
                } else {
                    callback();
                }
            }
        }
    ],
    manyUserUUID: [
        {
            required: true,
            message: "请选择安排人",
            trigger: "change",
            validator: (_rule: any, value: any, callback: any) => {
                if (isEditMode.value && (!value || value.trim() === '')) {
                    callback(new Error('请选择安排人'));
                } else {
                    callback();
                }
            }
        }
    ],
    oneToManyJob: [
        { required: true, message: "请输入任务内容", trigger: "blur" },
        { min: 5, message: "任务内容至少5个字符", trigger: "blur" },
    ],
    oneToManyTime: [{ required: true, message: "请选择完成时间", trigger: "change" }],
};

// 初始化任务数据
onMounted(() => {
    loading.value = true;
    getAgencyList();
});

// 禁用今天之前的日期
const disabledDate = (time: Date) => {
    return time.getTime() < Date.now() - 86400000;
};

// 处理时区问题的工具函数
const parseTaskTime = (timeString: string) => {
    // 如果时间字符串已经是正确的格式，直接解析
    if (timeString.includes('T') || timeString.includes('+')) {
        return new Date(timeString);
    }
    // 否则添加时区信息（假设服务器时间是东八区）
    return new Date(timeString.replace(' ', 'T') + '+08:00');
};


// 检查任务是否超时
const isTaskOverdue = (timeString: string) => {
    const currentTime = new Date();
    const taskEndTime = parseTaskTime(timeString);
    return currentTime > taskEndTime;
};

// 统一控制超时显示：已完成也根据 overtimeReason 判断
const isOvertimeDisplay = (row: any) => {
    if (row && typeof row.overtimeReason === 'string' && row.overtimeReason.trim().length > 0) {
        return true;
    }
    // 兼容未完成任务依旧走时间判断
    if (row && row.isTrue1 != 2) {
        return isTaskOverdue(row.oneToManyTime);
    }
    return false;
};

// 监听时间变化，用于调试
watch(() => taskForm.oneToManyTime, (newValue, oldValue) => {
    if (newValue) {
        console.log('时间变化:', {
            oldValue: oldValue,
            newValue: newValue,
            timestamp: new Date().toLocaleTimeString()
        });
    }
});


// 新增任务
const handleAddTask = () => {
    getItemList();
    getAllUsers();
    currentTaskId.value = 0;
    isEditMode.value = false;
    // 重置表单（特别是清空多选数组）
    taskForm.manyUserUUIDS = [] as string[];
    taskForm.manyUserUUID = "";
    showEditDialog.value = true;
};

// 编辑任务
const editTask = (task: Task) => {
    // 检查任务是否已完成
    if (task.isTrue1 == 2) {
        ElMessage.warning('已完成的任务不允许编辑');
        return;
    }
    
    getItemList();
    getAllUsers();
    isEditMode.value = true;
    currentTaskId.value = task.ID;

    // 填充表单数据
    taskForm.itemId = task.itemId;
    taskForm.manyUserUUID = task.manyUserUUID.split(',')[0] || ""; // 只取第一个
    taskForm.oneToManyJob = task.oneToManyJob;
    taskForm.oneToManyTime = task.oneToManyTime;

    showEditDialog.value = true;
};



// 完成任务
const completeTask = async (row: any) => {
    // 检查任务是否已完成
    if (row.isTrue1 == 2) {
        ElMessage.warning('该任务已完成');
        return;
    }
    
    // 检查是否超时
    const currentTime = new Date();
    const taskEndTime = parseTaskTime(row.oneToManyTime);
    
    if (currentTime > taskEndTime) {
        // 超时情况：直接使用自定义超时对话框进行一次性填写
        currentOvertimeRow.value = row;
        overtimeReason.value = '';
        showOvertimeDialog.value = true;
    } else {
        // 未超时，正常完成
        ElMessageBox.confirm("确定要完成该任务吗？", "提示", {
            confirmButtonText: "确认完成",
            cancelButtonText: "取消",
            type: "success",
        }).then(async () => {
            // 调用完成任务的API（POST）
            const { data } = await OverAgencyById({ id: row.ID });
            
            if (data.code == 200) {
                ElMessage.success('任务已完成');
                getAgencyList();
            } else {
                ElMessage.error(data.msg);
            }
        }).catch(() => {
            ElMessage.info("已取消完成");
        });
    }
};

// 删除任务
const deleteTask = async (row: any) => {
    // 检查任务是否已完成
    if (row.isTrue1 == 2) {
        ElMessage.warning('已完成的任务不允许删除');
        return;
    }
    
    ElMessageBox.confirm("确定要删除该任务吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const { data } = await DeleteAgencyById(row.ID)
        if (data.code == 200) {
            ElMessage.success(data.msg)
            getAgencyList()
        } else {
            ElMessage.error(data.msg)
        }
    }).catch(() => {
        ElMessage.info("取消删除");
    });
};


// 提交任务
const submitTask = () => {
    taskFormRef.value?.validate((valid) => {
        if (valid) {
            if (isEditMode.value) {
                // 更新现有任务
                if (currentTaskId.value == 0) {
                    ElMessage.error("编辑数据不合法")
                    return
                } else {
                    createUpdateAgency()
                }
            } else {
                // 添加新任务
                createUpdateAgency();
            }

            showEditDialog.value = false;
            resetForm();
        }
    });
};

// 创建代办数据
const createUpdateAgency = async () => {
    console.log('提交时的时间:', taskForm.oneToManyTime);
    
    // 由于后台会自动增加8小时，我们需要在前端减去8小时来补偿
    let correctedTime = taskForm.oneToManyTime;
    if (taskForm.oneToManyTime) {
        const date = new Date(taskForm.oneToManyTime);
        // 减去8小时来补偿后台的时区转换
        const correctedDate = new Date(date.getTime() - 8 * 60 * 60 * 1000);
        
        const year = correctedDate.getFullYear();
        const month = String(correctedDate.getMonth() + 1).padStart(2, '0');
        const day = String(correctedDate.getDate()).padStart(2, '0');
        const hours = String(correctedDate.getHours()).padStart(2, '0');
        const minutes = String(correctedDate.getMinutes()).padStart(2, '0');
        const seconds = String(correctedDate.getSeconds()).padStart(2, '0');
        correctedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        console.log('补偿后台时区转换后的时间:', correctedTime);
    }
    
    const submitData = {
        itemId: taskForm.itemId,
        oneToManyJob: taskForm.oneToManyJob,
        oneToManyTime: correctedTime, // 使用补偿后的时间
        currentTaskId: currentTaskId.value,
        manyUserUUID: "",
        manyUserUUIDS: [] as string[],
    };

    if (isEditMode.value) {
        // 编辑模式：使用 manyUserUUID (字符串)
        submitData.manyUserUUID = taskForm.manyUserUUID;
    } else {
        // 新增模式：使用 manyUserUUIDS (数组转字符串)
        submitData.manyUserUUIDS = taskForm.manyUserUUIDS;
    }
    const { data } = await CreateUpdateAgency(submitData)
    if (data.code == 200) {
        ElMessage.success(data.msg)
        getAgencyList()
    } else {
        ElMessage.error(data.msg)
    }
}



// 重置表单
const resetForm = () => {
    taskFormRef.value?.resetFields();
    isEditMode.value = false;
};

// 筛选任务
const handleFilter = () => {
    currentPage.value = 1;
    getAgencyList(); // 立即执行过滤查询
};

// 分页大小变化
const handleSizeChange = (val: number) => {
    pageSize.value = val;
};

// 当前页变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
};
</script>

<style scoped>
/* 主容器 */
.task-management-container {
    width: 100%;
    min-height: 100vh;
    padding: 0;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    box-sizing: border-box;
}

/* 页面头部 */
.page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    padding: 20px 32px;
    margin: 16px 16px 0 16px;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
    color: white;
}

.header-content {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.header-right {
    display: flex;
    align-items: center;
}

.add-task-btn {
    background: rgba(255, 255, 255, 0.2);
    border: 2px solid rgba(255, 255, 255, 0.3);
    color: white;
    font-weight: 600;
    padding: 12px 24px;
    border-radius: 12px;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
}

.add-task-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 255, 255, 0.5);
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

/* 筛选工具栏 */
.filter-toolbar {
    background: white;
    border-radius: 12px;
    margin: 16px 16px 0 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    border: 1px solid #f1f5f9;
    overflow: hidden;
}

.filter-section {
    display: flex;
    align-items: center;
    padding: 16px 20px;
    gap: 24px;
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 12px;
}

.filter-label {
    font-size: 14px;
    font-weight: 600;
    color: #374151;
    white-space: nowrap;
    min-width: fit-content;
}

.filter-divider {
    width: 1px;
    height: 32px;
    background: linear-gradient(to bottom, transparent, #e2e8f0, transparent);
}

.compact-radio-group {
    display: flex;
    gap: 8px;
}

.compact-radio {
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.2s ease;
}

.compact-radio :deep(.el-radio-button__inner) {
    padding: 8px 16px;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    background: white;
    color: #64748b;
    font-weight: 500;
    font-size: 13px;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 6px;
    min-height: 32px;
}

.compact-radio :deep(.el-radio-button__inner:hover) {
    border-color: #3b82f6;
    color: #3b82f6;
    background: #f8fafc;
}

.compact-radio :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border-color: #3b82f6;
    color: white;
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.25);
}

/* 表格卡片 */
.table-card {
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: none;
    overflow: hidden;
    margin: 16px 16px 16px 16px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-bottom: 1px solid #e2e8f0;
}

.table-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;
}

.table-stats {
    display: flex;
    align-items: center;
    gap: 16px;
}

.stats-item {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #64748b;
    font-size: 14px;
}

/* 现代化表格 */
.modern-table {
    border: none;
}

.modern-table :deep(.el-table__body-wrapper) {
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f1f1f1;
}

.modern-table :deep(.el-table__body-wrapper)::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

.modern-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.modern-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.modern-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.modern-table :deep(.el-table__header) {
    background: #f8fafc;
}

.modern-table :deep(.el-table__header th) {
    background: #f8fafc;
    border-bottom: 2px solid #e2e8f0;
    color: #374151;
    font-weight: 600;
    padding: 16px 12px;
    text-align: center;
}

.modern-table :deep(.el-table__body tr) {
    transition: all 0.2s ease;
}

.modern-table :deep(.el-table__body tr:hover) {
    background: #f8fafc;
    transform: scale(1.01);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.modern-table :deep(.el-table__body td) {
    padding: 16px 12px;
    border-bottom: 1px solid #f1f5f9;
}

/* 表格单元格样式 */
.project-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.project-icon {
    color: #3b82f6;
    font-size: 16px;
}

.project-name {
    font-weight: 500;
    color: #1e293b;
}

.assignee-cell {
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: center;
}

.assignee-tag {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 4px 8px;
    background: #f1f5f9;
    border-radius: 8px;
    width: fit-content;
}

.assignee-avatar {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
    font-weight: 600;
}

.assignee-name {
    font-size: 14px;
    color: #374151;
}

.task-content {
    max-width: 100%;
}

.task-text {
    margin: 0;
    color: #374151;
    line-height: 1.5;
    word-wrap: break-word;
    word-break: break-word;
    white-space: pre-wrap;
}

.overtime-badge {
    display: inline-block;
    margin-left: 6px;
    padding: 2px 6px;
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
    font-size: 10px;
    font-weight: 700;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(239, 68, 68, 0.3);
    animation: pulse-badge 2s infinite;
    vertical-align: middle;
}

.time-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.time-icon {
    color: #64748b;
    font-size: 14px;
    transition: color 0.3s ease;
}

.time-icon.overtime-icon {
    color: #ef4444;
    animation: pulse-red 2s infinite;
}

.time-text {
    color: #374151;
    font-size: 14px;
    transition: color 0.3s ease;
}

.time-text.overtime-text {
    color: #ef4444;
    font-weight: 600;
    animation: pulse-red 2s infinite;
}

@keyframes pulse-red {
    0%, 100% {
        opacity: 1;
    }
    50% {
        opacity: 0.7;
    }
}

@keyframes pulse-badge {
    0%, 100% {
        box-shadow: 0 1px 3px rgba(239, 68, 68, 0.3);
        transform: scale(1);
    }
    50% {
        box-shadow: 0 2px 6px rgba(239, 68, 68, 0.5);
        transform: scale(1.05);
    }
}

.status-tag {
    border-radius: 20px;
    padding: 6px 12px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 4px;
}

.status-completed {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
}

.status-pending {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: white;
}

.action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
}

.action-btn {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.2s ease;
}

.action-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.edit-btn {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;
}

.edit-btn:disabled {
    background: #e2e8f0;
    color: #94a3b8;
    cursor: not-allowed;
    opacity: 0.6;
}

.edit-btn:disabled:hover {
    background: #e2e8f0;
    color: #94a3b8;
    transform: none;
    box-shadow: none;
}

.delete-btn {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    border: none;
}

.delete-btn:disabled {
    background: #e2e8f0;
    color: #94a3b8;
    cursor: not-allowed;
    opacity: 0.6;
}

.delete-btn:disabled:hover {
    background: #e2e8f0;
    color: #94a3b8;
    transform: none;
    box-shadow: none;
}

.complete-btn {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border: none;
}

.complete-btn:disabled {
    background: #e2e8f0;
    color: #94a3b8;
    cursor: not-allowed;
    opacity: 0.6;
}

.complete-btn:disabled:hover {
    background: #e2e8f0;
    color: #94a3b8;
    transform: none;
    box-shadow: none;
}

/* 分页 */
.pagination-wrapper {
    padding: 24px;
    display: flex;
    justify-content: flex-end;
    background: #f8fafc;
    border-top: 1px solid #e2e8f0;
}

.modern-pagination :deep(.el-pagination) {
    justify-content: flex-end;
}

.modern-pagination :deep(.el-pager li) {
    border-radius: 8px;
    margin: 0 4px;
    transition: all 0.2s ease;
}

.modern-pagination :deep(.el-pager li:hover) {
    background: #e2e8f0;
    transform: translateY(-1px);
}

.modern-pagination :deep(.el-pager li.is-active) {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
}

/* 对话框样式 */
.task-dialog :deep(.el-dialog) {
    border-radius: 20px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
    border: none;
    overflow: hidden;
}

.task-dialog :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 24px 32px;
    margin: 0;
    border-bottom: none;
}

.dialog-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 20px;
    font-weight: 600;
}

.dialog-icon {
    font-size: 24px;
}

.task-dialog :deep(.el-dialog__body) {
    padding: 32px;
    background: #f8fafc;
}

.task-form {
    background: white;
    padding: 24px;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.task-dialog :deep(.el-form-item__label) {
    font-weight: 600;
    color: #374151;
    font-size: 14px;
}

.form-select,
.form-textarea,
.form-datepicker {
    border-radius: 12px;
    border: 2px solid #e2e8f0;
    transition: all 0.3s ease;
}

.form-select :deep(.el-input__inner),
.form-textarea :deep(.el-textarea__inner),
.form-datepicker :deep(.el-input__inner) {
    border: none;
    border-radius: 12px;
    padding: 12px 16px;
    font-size: 14px;
}

.form-select :deep(.el-input__inner:focus),
.form-textarea :deep(.el-textarea__inner:focus),
.form-datepicker :deep(.el-input__inner:focus) {
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.option-content {
    display: flex;
    align-items: center;
    gap: 8px;
}

.task-dialog :deep(.el-dialog__footer) {
    padding: 24px 32px;
    background: #f8fafc;
    border-top: 1px solid #e2e8f0;
    text-align: right;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.cancel-btn,
.confirm-btn {
    border-radius: 12px;
    padding: 12px 24px;
    font-weight: 600;
    transition: all 0.3s ease;
}

.cancel-btn {
    background: #f1f5f9;
    border: 2px solid #e2e8f0;
    color: #64748b;
}

.cancel-btn:hover {
    background: #e2e8f0;
    transform: translateY(-2px);
}

.confirm-btn {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;
    color: white;
}

.confirm-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
}

/* 超时原因对话框提示 */
.overtime-tip {
    margin-bottom: 12px;
    font-size: 13px;
    color: #ef4444;
}

/* 优化的超时对话框样式 */
.overtime-dialog :deep(.el-dialog__header){
    margin:0;
}
.overtime-dialog .overtime-dialog-header{
    display:flex;
    align-items:center;
    gap:12px;
    padding:14px 20px;
    background:linear-gradient(135deg,#fef3c7 0%, #fde68a 100%);
    border-bottom:1px solid #fde68a;
}
.overtime-dialog .overtime-dialog-icon{
    color:#f59e0b;
    font-size:20px;
}
.overtime-dialog .overtime-dialog-titles .title{
    font-size:16px;
    font-weight:700;
    color:#92400e;
}
.overtime-dialog .overtime-dialog-titles .subtitle{
    font-size:12px;
    color:#b45309;
}
.overtime-body{
    padding:16px 20px 0 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .page-header {
        padding: 16px 24px;
        margin: 12px 12px 0 12px;
    }
    
    .filter-toolbar {
        margin: 12px 12px 0 12px;
    }
    
    .table-card {
        margin: 12px 12px 12px 12px;
    }
}

@media (min-width: 1400px) {
    .page-header {
        padding: 24px 40px;
        margin: 20px 20px 0 20px;
    }
    
    .filter-toolbar {
        margin: 20px 20px 0 20px;
    }
    
    .table-card {
        margin: 20px 20px 20px 20px;
    }
}

@media (max-width: 768px) {
    .page-header {
        padding: 16px 20px;
        margin: 8px 8px 0 8px;
        border-radius: 12px;
    }
    
    .filter-toolbar {
        margin: 8px 8px 0 8px;
        border-radius: 8px;
    }
    
    .table-card {
        margin: 8px 8px 8px 8px;
        border-radius: 12px;
    }
    
    .modern-table {
        max-height: 500px;
    }
    
    .filter-section {
        flex-direction: column;
        align-items: stretch;
        gap: 16px;
        padding: 16px;
    }
    
    .filter-item {
        flex-direction: column;
        align-items: stretch;
        gap: 8px;
    }
    
    .filter-label {
        font-size: 13px;
        margin-bottom: 4px;
    }
    
    .filter-divider {
        width: 100%;
        height: 1px;
        background: linear-gradient(to right, transparent, #e2e8f0, transparent);
    }
    
    .compact-radio-group {
        justify-content: center;
        flex-wrap: wrap;
    }
    
    .compact-radio {
        flex: 1;
        min-width: 0;
    }
    
    .compact-radio :deep(.el-radio-button__inner) {
        padding: 8px 12px;
        font-size: 12px;
        justify-content: center;
    }
    
    .task-dialog :deep(.el-dialog) {
        width: 95% !important;
        margin: 5vh auto;
    }
    
    .task-dialog :deep(.el-dialog__body) {
        padding: 20px;
    }
    
    .task-form {
        padding: 16px;
    }
    
    .action-buttons {
        flex-direction: column;
    }
    
    .action-btn {
        width: 100%;
    }
}

@media (max-width: 480px) {
    .page-header {
        padding: 12px 16px;
        margin: 6px 6px 0 6px;
        border-radius: 8px;
    }
    
    .filter-toolbar {
        margin: 6px 6px 0 6px;
        border-radius: 6px;
    }
    
    .table-card {
        margin: 6px 6px 6px 6px;
        border-radius: 8px;
    }
    
    .filter-section {
        padding: 16px;
    }
    
    .table-header {
        padding: 16px;
        flex-direction: column;
        gap: 12px;
    }
}
</style>